//
//  WFChannelViewController.m
//  FAKER
//
//  Created by Jianwei on 15/11/4.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "WFChannelViewController.h"
#import "AllHeader.h"
#import "FitHeader.h"
#import "BaseClassLabel.h"
#import "BaseClassScrollView.h"
#import "WFSelectedTableView.h"
#import "WFChannelTableView.h"
#import "BaseClassView.h"
#import "WFSecondChannelViewController.h"
#import "YHSearchCollectionCell.h"
#import "YHSearchResultViewController.h"
#import "WFThisWeekNewestChannelOnLineViewController.h"
#import "WFSelectedView.h"
#import "WFChannelDetailViewController.h"
//热门搜索
#define HOTSEARCH_URLSTRING @"http://search.myzaker.com/api/?_appid=iphone&c=keywords"

@interface WFChannelViewController ()<UIScrollViewDelegate, WFChannelTableViewDelegate, UISearchBarDelegate, WFSelectedViewDelegate, WFSelecteTableViewDelegate>//<UICollectionViewDataSource, UICollectionViewDelegate>
//@property(nonatomic, strong)BaseClassCollectionView *backCollectionView;
@property(nonatomic, strong)BaseClassScrollView *scrollView;
@property(nonatomic, strong)BaseClassLabel *selectedLabel;
@property(nonatomic, strong)BaseClassLabel *channelLabel;
@property(nonatomic, strong)WFSelectedTableView *selectedTableView;
@property(nonatomic, strong)WFChannelTableView *channelTableView;
@property(nonatomic, strong)UIView *lineView;
@property(nonatomic, strong)UISearchBar *searchBar;//搜索条
@property(nonatomic, strong)UIView *searchResultView;//搜索界面
@property(nonatomic, strong)NSMutableArray *hotSearchArray;//热门搜索数组
@property(nonatomic, strong)UICollectionView *searchCollectionView;//搜索collectionView
@property(nonatomic, strong)UICollectionViewFlowLayout *hotSearchFlowLayout;
@property(nonatomic, strong)NSMutableArray *allCellArray;
@property(nonatomic, strong)UILabel *headerLabel;
@property(nonatomic, strong)YHLoadingView *loadingView;
@end

@implementation WFChannelViewController
- (void)pushViewWithUrlString:(NSString *)urlString
{
    WFChannelDetailViewController *wc = [[WFChannelDetailViewController alloc]init];
    wc.api_url = urlString;
    [self.navigationController pushViewController:wc animated:1];
}

- (void)pushViewWithWFSelectViewModel:(WFSelectedViewModel *)model
{
    if (model.block_topic) {
        WFThisWeekNewestChannelOnLineViewController *wc = [[WFThisWeekNewestChannelOnLineViewController alloc]init];
        wc.model = model;
        [self.navigationController pushViewController:wc animated:1];
    } else {
        WFChannelDetailViewController *wc = [[WFChannelDetailViewController alloc]init];
        wc.api_url = [model.block_info objectForKey:@"api_url"];
        [self.navigationController pushViewController:wc animated:1];
    }
}

- (void)pushSecondChannelViewController:(WFChannelListModel *)model
{
    WFSecondChannelViewController *wc = [WFSecondChannelViewController alloc];
    wc.model = model;
    [self.navigationController pushViewController:wc animated:1];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _allCellArray = [NSMutableArray array];
    
    //创建加载中视图
    _loadingView = [[YHLoadingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    [self.view addSubview:_loadingView];
    
    //创建搜索
    [self createSearchBar];
    //添加夜间模式监听
    [self changeColor];
    ADD_NSNOTIFICATIONCENTER_OBSERVER;
}
- (void)yhRemoveLoadingView
{
    [_loadingView removeFromSuperview];
}
- (void)loadView
{
    [super loadView];
    
    _scrollView = [[BaseClassScrollView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 40)];
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, _scrollView.HEIGHT);
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    _selectedTableView = [[WFSelectedTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _scrollView.HEIGHT)];
    _selectedTableView.delegate = self;
    WFSelectedView *selectedView = [[WFSelectedView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150 * FITWIDTH)];
    selectedView.delegate = self;
    _selectedTableView.selectedTableView.tableHeaderView = selectedView;
    [_scrollView addSubview:_selectedTableView];
    
    _channelTableView = [[WFChannelTableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, _selectedTableView.WIDTH, _scrollView.HEIGHT)];
    _channelTableView.delegate = self;
    [_scrollView addSubview:_channelTableView];
    
    _selectedLabel = [[BaseClassLabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 39)];
    _selectedLabel.text = @"精选";
    _selectedLabel.textAlignment = 1;
    _selectedLabel.textColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
    _selectedLabel.font = [UIFont systemFontOfSize:15];
    _selectedLabel.tag = 1000;
    _selectedLabel.userInteractionEnabled = 1;
     UITapGestureRecognizer *selectedTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [_selectedLabel addGestureRecognizer:selectedTap];
    [self.view addSubview:_selectedLabel];
    
    _channelLabel = [[BaseClassLabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2, 0, _selectedLabel.WIDTH, _selectedLabel.HEIGHT)];
    _channelLabel.text = @"频道";
    _channelLabel.textAlignment = 1;
    _channelLabel.textColor = [UIColor grayColor];
    _channelLabel.font = [UIFont systemFontOfSize:15];
    _channelLabel.tag = 1001;
    _channelLabel.userInteractionEnabled = 1;
    UITapGestureRecognizer *channelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [_channelLabel addGestureRecognizer:channelTap];
    [self.view addSubview:_channelLabel];
    
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, _selectedLabel.Y + _selectedLabel.HEIGHT, SCREEN_WIDTH, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lineView];
    
    _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, _selectedLabel.Y + _selectedLabel.HEIGHT - 1, _selectedLabel.WIDTH, 2)];
    _lineView.backgroundColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
    if (NSUSERDEFAULTS_NIGHT) {

        _lineView.backgroundColor = [UIColor lightGrayColor];
        lineView.backgroundColor = [UIColor grayColor];
        _selectedLabel.textColor = [UIColor grayColor];
        _channelLabel.textColor = [UIColor grayColor];
    }
    [self.view addSubview:_lineView];
//    UICollectionViewFlowLayout *backCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc]init];
//    backCollectionViewFlowLayout.itemSize = CGSizeMake(SCREEN_WIDTH * FITWIDTH, 637 * FITHEIGHT);
//    backCollectionViewFlowLayout.minimumInteritemSpacing = 0;
//    backCollectionViewFlowLayout.minimumLineSpacing = 0;
//    backCollectionViewFlowLayout.scrollDirection = 1;
//    
//    _backCollectionView = [[BaseClassCollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * FITWIDTH, 637 * FITHEIGHT) collectionViewLayout:backCollectionViewFlowLayout];
//    _backCollectionView.pagingEnabled = 1;
//    _backCollectionView.dataSource = self;
//    _backCollectionView.delegate = self;
//    [_backCollectionView registerClass:[WFChannelDetailCollectionViewCell class] forCellWithReuseIdentifier:@"back"];
//    
//    [self.view addSubview:_backCollectionView];
}
//- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    WFChannelDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"back" forIndexPath:indexPath];
//    return cell;
//}
//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
//{
//    return 5;
//}
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (tap.view.tag == 1000) {
        _selectedLabel.textColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
        _channelLabel.textColor = [UIColor grayColor];
        if (NSUSERDEFAULTS_NIGHT) {
            _selectedLabel.textColor = [UIColor lightGrayColor];
            _channelLabel.textColor = [UIColor grayColor];
        }
        [UIView animateWithDuration:.5 animations:^{
            _lineView.frame = CGRectMake(0, _selectedLabel.Y + _selectedLabel.HEIGHT - 1, _selectedLabel.WIDTH, 2);
            _scrollView.contentOffset = CGPointMake(0, 0);
        } completion:^(BOOL finished) {
            
        }];
    }
    else
    {
        _channelLabel.textColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
        _selectedLabel.textColor = [UIColor grayColor];
        if (NSUSERDEFAULTS_NIGHT) {
            _selectedLabel.textColor = [UIColor grayColor];
            _channelLabel.textColor = [UIColor lightGrayColor];
        }
        [UIView animateWithDuration:.5 animations:^{
            _lineView.frame = CGRectMake(SCREEN_WIDTH / 2, _selectedLabel.Y + _selectedLabel.HEIGHT - 1, _selectedLabel.WIDTH, 2);
            _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        } completion:^(BOOL finished) {
            
        
        }];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == 0) {
        _selectedLabel.textColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
        _channelLabel.textColor = [UIColor grayColor];
        if (NSUSERDEFAULTS_NIGHT) {
            _selectedLabel.textColor = [UIColor lightGrayColor];
            _channelLabel.textColor = [UIColor grayColor];
        }
        [UIView animateWithDuration:.3 animations:^{
            _lineView.frame = CGRectMake(0, _selectedLabel.Y + _selectedLabel.HEIGHT - 1, _selectedLabel.WIDTH, 2);
            _scrollView.contentOffset = CGPointMake(0, 0);
        } completion:^(BOOL finished) {
            
        }];
    }
    else
    {
        _channelLabel.textColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
        _selectedLabel.textColor = [UIColor grayColor];
        if (NSUSERDEFAULTS_NIGHT) {
            _selectedLabel.textColor = [UIColor grayColor];
            _channelLabel.textColor = [UIColor lightGrayColor];
        }
        [UIView animateWithDuration:.3 animations:^{
            _lineView.frame = CGRectMake(SCREEN_WIDTH / 2, _selectedLabel.Y + _selectedLabel.HEIGHT - 1, _selectedLabel.WIDTH, 2);
            _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        } completion:^(BOOL finished) {
            
            
        }];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = 0;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - searchBar
#pragma mark 获取数据
- (void)getData
{
    [InternetDataRequest getDataByString:HOTSEARCH_URLSTRING BodyDic:nil WithDataBlock:^(id data) {
        NSArray *wordsArray = [[[[(NSDictionary *)data objectForKey:@"data"] objectForKey:@"wordlist"] firstObject] objectForKey:@"words"];
        for (NSDictionary *dict in wordsArray) {
            [_hotSearchArray addObject:[dict objectForKey:@"text"]];
        }
        [_searchCollectionView reloadData];
    }];
}
#pragma mark 创建搜索
- (void)createSearchBar
{
    //创建搜索条
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.placeholder = @"搜索文章和频道";
    _searchBar.contentMode = UIViewContentModeLeft;
    _searchBar.delegate = self;
    self.navigationItem.titleView = _searchBar;
    
    //获取数据
    _hotSearchArray = [NSMutableArray array];
    [self getData];
    
    //创建搜索界面
    _searchResultView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _searchResultView.hidden = YES;
//    _searchResultView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_searchResultView];
    
    //创建头视图
    _headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH - 20, 50)];
    _headerLabel.text = @"热门搜索";
    _headerLabel.font = [UIFont systemFontOfSize:15];
    [_searchResultView addSubview:_headerLabel];
    
    //创建搜索collectionView
    _hotSearchFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    _hotSearchFlowLayout.minimumInteritemSpacing = 20;
    _hotSearchFlowLayout.minimumLineSpacing = 15;
    _hotSearchFlowLayout.sectionInset = UIEdgeInsetsMake(0, 20, 15, 20);
    
    _searchCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _headerLabel.HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - _headerLabel.HEIGHT) collectionViewLayout:_hotSearchFlowLayout];
    _searchCollectionView.dataSource = self;
    _searchCollectionView.delegate = self;
    _searchCollectionView.backgroundColor = [UIColor whiteColor];
    [_searchResultView addSubview:_searchCollectionView];
    [_searchCollectionView registerClass:[YHSearchCollectionCell class] forCellWithReuseIdentifier:@"search"];
}

#pragma mark - collection
#pragma mark cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _hotSearchArray.count;
}
#pragma mark cell样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YHSearchCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"search" forIndexPath:indexPath];
    
    //修改cell的frame
    [_allCellArray addObject:cell];
    if (indexPath.row != 0) {
        if (cell.frame.origin.x != 20) {
            YHSearchCollectionCell *preCell = _allCellArray[indexPath.row - 1];
            cell.frame = CGRectMake(preCell.frame.origin.x + preCell.frame.size.width + 20, preCell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        }
    }
    
    cell.titleLabel.text = _hotSearchArray[indexPath.row];
//    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
#pragma mark cell大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake([Adaptive AdaptiveWidthByString:_hotSearchArray[indexPath.row] Height:25 FontSize:14] + 20, 30);
}
#pragma mark cell点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _searchBar.text = _hotSearchArray[indexPath.row];
    [_searchBar resignFirstResponder];
    YHSearchResultViewController *searchResultVC = [[YHSearchResultViewController alloc] init];
    searchResultVC.searchKeyword = _searchBar.text;
    [self.navigationController pushViewController:searchResultVC animated:YES];
}

#pragma mark - 代理方法
#pragma mark 点击键盘搜索键
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
    YHSearchResultViewController *searchResultVC = [[YHSearchResultViewController alloc] init];
    searchResultVC.searchKeyword = _searchBar.text;
    [self.navigationController pushViewController:searchResultVC animated:YES];
}
#pragma mark 点击searchBar
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //创建取消按钮
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(clickCancerButtonAction)] animated:YES];
    //隐藏返回键
    [self.navigationItem setHidesBackButton:YES animated:NO];
    //显示搜索界面
    [_searchResultView setHidden:NO];
    return YES;
}

#pragma mark - 点击方法
#pragma mark 点击取消按钮
- (void)clickCancerButtonAction
{
    //失去第一响应者
    [_searchBar resignFirstResponder];
    //隐藏搜索界面
    [_searchResultView setHidden:YES];
    //显示返回键
    [self.navigationItem setHidesBackButton:NO animated:YES];
    //移除取消按钮
    [self.navigationItem setRightBarButtonItem:nil animated:YES];
    //删除searchBar上文字
    _searchBar.text = nil;
}

#pragma mark - 改变颜色
- (void)changeColor
{
    if (NSUSERDEFAULTS_NIGHT) {
        _searchResultView.backgroundColor = BGCOLOR_BLACK;
        _searchCollectionView.backgroundColor = BGCOLOR_BLACK;
        _headerLabel.textColor = [UIColor lightGrayColor];
    }
    else {
        _searchResultView.backgroundColor = BGCOLOR_WHITE;
        _searchCollectionView.backgroundColor = BGCOLOR_WHITE;
        _headerLabel.textColor = [UIColor blackColor];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
